/**   
* 所属公司：稻普控股集团
* @Title: BaseController.java 
* @Package com.base.controller 
* @author zhangpp
* @date 2017年3月24日 下午12:53:26 
* @version V1.0   
*/
package com.zjdiepu.www.base;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.DateTypeEditor;
import com.zjdiepu.www.base.core.PageExt;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.TypeData;
import com.zjdiepu.www.common.consts.SystemConsts;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.commpent.helper.UserMapSalermanHelper;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.system.IBaseSysParamsService;
import com.zjdiepu.www.ibiz.zx.IZxCreditQueryService;
import com.zjdiepu.www.model.other.dto.OtherMessageApp;
import com.zjdiepu.www.model.other.response.OtherMessageAppResponse;
import com.zjdiepu.www.model.other.response.OtherMessageAppResponseItem;
import com.zjdiepu.www.model.zx.dto.ZxCreditQuery;
import com.zjdiepu.www.util.CachedEnums;
import com.zjdiepu.www.util.ExceptionHelper;

/**   
 * 所属公司：稻普控股集团
 * 项目名称：dpqc-parent-manager-base   
 * 类名称：BaseController   
 * 类描述：   
 * 创建人：zhangpp
 * 创建时间：2017年3月24日 下午12:53:26   
 * 修改人：zhangpp
 * 修改时间：2017年3月24日 下午12:53:26   
 * 修改备注：   
 * @version V1.0     
 */
@Controller
public class BaseController {
	@Resource
	protected RedisObjectClient redisObjectClient;
	@Resource
	protected ICachedDictionaryService cachedDictionaryService;
	@Resource
	protected UserMapSalermanHelper userMapSalermanHelper;
	@Resource
	protected IZxCreditQueryService zxCreditQueryService;
	
	/**
	 * 当前登录用户
	 */
	public static final String CURRENT_USER_KEY = "current_user_key";
	
	@Resource
	private IBaseSysParamsService baseSysParamsService;
	@Resource
	protected HttpServletRequest request;
	
	protected AbstractSysUser getCurrentUser(){
		HttpSession session = request.getSession(true);
		Object currentUser = session.getAttribute(CURRENT_USER_KEY);
		if(null == currentUser){
			ExceptionHelper.thow(ResultFlagType.LOGIN_TIMEOUT);
		}
		return (AbstractSysUser)currentUser;
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getCurrentUser  <br/>
	 * @Description: 退出登录 <br/>
	 * @return
	 * @version V1.0  <br/>
	 */
	public void removeCurrentUser(){
		HttpSession session = request.getSession(false);
		session.removeAttribute(CURRENT_USER_KEY);
		session.invalidate();
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: isSuperRole  <br/>
	 * @Description: 判断是否为超级管理员公司、部门、用户、角色 <br/>
	 * @param currentUser
	 * @return
	 * @version V1.0  <br/>
	 */
	protected static boolean isSuper(String id){
		if(StringUtils.isBlank(id)) {
			return false;
		}
		return SystemConsts.SUPER_ADMIN_ID.equals(id);
	}
	
	/**
	 * 判断是否为IE
	 * @author xiongxiaotun <br/>
	 * @Title isIE  <br/>
	 * @Description 判断是否为IE <br/>
	 * @param request
	 * @return
	 * @version V1.0  <br/>
	 */
	protected boolean isIE(HttpServletRequest request) {
		String agent = request.getHeader("User-Agent").toLowerCase();
		if (agent.indexOf("msie") > 0) {
			return true;
		}
		return false;
	}
	
	/**
	 *  返回值定义    dpqc-parent

		flag 错误  标示
		
		100100  成功执行
		
		100200  失败 出错
		
		100300  数据未找到
		
		100400  秘钥错误
		
		100500  参数为空
		
		message  详细错误输出字段

	 */
	
	
	private static final Logger logger = LoggerFactory.getLogger(BaseController.class);
	public static final String REDIRECT = "redirect:";
	public static final String FORWARD = "forward:";
	
	/**重定向：重请求
	 * @throws IOException */
	protected void redirect(HttpServletRequest request, HttpServletResponse response, String action) throws IOException {
		response.sendRedirect(request.getContextPath() +  action);
	}
	
	/**重定向：站内*/
	protected String forward(String action) {
		return FORWARD + action;
	}
	
	//成功
	public Map<String, Object> success()
	{
		Map<String, Object> maps = CollectionInitUtil.emptyMap();
		maps.put("flag", 100100);
		maps.put("message", "系统检测，本次执行成功！【稻普控股集团】");
		return maps;
	}

	
	//错误
	public Map<String, Object> errorMassage(Exception e,String message)
	{
		logger.error("------------错误开始------------");
		logger.error("异常:", e);
		logger.error(message);
		logger.error("100200");
		logger.error("------------错误结束------------");
		Map<String, Object> maps = CollectionInitUtil.emptyMap();
		maps.put("flag",100200);
		maps.put("message",e);
		return maps;
	}
	
	//警告
	public Map<String, Object> errorMassage(String message,int flag)
	{
		logger.error("------------自定义警告开始------------");
		logger.error(message);
		logger.error(String.valueOf(flag));
		logger.error("------------自定义警告结束------------");
		Map<String, Object> maps = CollectionInitUtil.emptyMap();
		maps.put("flag",flag);
		maps.put("message",message);
		return maps;
	}
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: getPage  <br/>
	 * @Description: 获取分页对象 <br/>
	 * @param ext 查询条件
	 * @return
	 * @version V1.0  <br/>
	 */
	protected PageVo getPage(PageExt ext){
		PageVo page = new PageVo();
		page.setPageSize(ext.getRows());
		page.setPage(ext.getPage());
		return page;
	}
	
	/**返回数据转换*/
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new DateTypeEditor());
    }
	
	@ModelAttribute
	public void prepared(Model model){
		String cssVersion = baseSysParamsService.getValueByCode("cssVersion");
		if(StringUtils.isNotBlank(cssVersion)) {
			model.addAttribute("cssVersion", cssVersion);
		} else {
			model.addAttribute("cssVersion", Math.random());
		}
	}
	
	/**
	   * 转换属性：展示
	   * @param ywBusinesss
	   * @return
	   */
	protected List<OtherMessageAppResponse> mapOtherMessageApps(
			List<OtherMessageApp> otherMessageApps) {
		List<OtherMessageAppResponse> otherMessageAppResponses = CollectionInitUtil.emptyList();
		if (CollectionUtils.isEmpty(otherMessageApps)) {
			return otherMessageAppResponses;
		}

		redisObjectClient.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection redisConnection)
					throws DataAccessException {
				String cuurentDateString = "";
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
				List<OtherMessageAppResponseItem> otherMessageAppResponseItems = CollectionInitUtil.emptyList();
				for (OtherMessageApp otherMessageApp : otherMessageApps) {
					Date timeCreate = otherMessageApp.getTimeCreate();
					if (timeCreate == null) {
						continue;
					}
					String tempDateString = simpleDateFormat.format(timeCreate);
					OtherMessageAppResponseItem otherMessageAppResponseItem = mapOtherMessageApp(redisConnection, otherMessageApp);
					if (!cuurentDateString.equals(tempDateString)) {
						OtherMessageAppResponse otherMessageAppResponse = new OtherMessageAppResponse();
						otherMessageAppResponseItems = CollectionInitUtil.emptyList();
						
						cuurentDateString = tempDateString;
						otherMessageAppResponse.setTimeCreate(cuurentDateString);
						otherMessageAppResponse.setOtherMessageAppResponseItems(otherMessageAppResponseItems);
						
						otherMessageAppResponses.add(otherMessageAppResponse);
					}
					otherMessageAppResponseItems.add(otherMessageAppResponseItem);
				}
				return null;
			}
		});
		return otherMessageAppResponses;
	}
  
  /**
   * 转换属性：展示
   * @param ywBusinesss
   * @return
   */
	protected OtherMessageAppResponseItem mapOtherMessageApp(RedisConnection redisConnection, OtherMessageApp otherMessageApp){
	  	if(otherMessageApp == null) {
	  		return null;
	  	}
		OtherMessageAppResponseItem otherMessageAppResponseItem = new OtherMessageAppResponseItem();
		BeanUtils.copyProperties(otherMessageApp, otherMessageAppResponseItem);
		otherMessageAppResponseItem.setTypeMsgEventName(cachedDictionaryService.getName(redisConnection, otherMessageApp.getTypeMsgEvent(), DataDicType.MESSAGE_EVENT_TYPE));
		otherMessageAppResponseItem.setModelName((String)CachedEnums.getValue(otherMessageApp.getModeId(), ModeIDType.class));
		String content = otherMessageAppResponseItem.getContent();
		otherMessageAppResponseItem.setContent((StringUtils.isBlank(content) ? "时间：" : content + "/n时间：") + DateUtil.dateTo14String(otherMessageAppResponseItem.getTimeSend()));
		//查看是否为接口查询征信
		ZxCreditQuery zxCreditQuery = zxCreditQueryService.selectById(otherMessageApp.getDataid());
		if(null != zxCreditQuery) {
			Integer typeData = zxCreditQuery.getTypeData();
			otherMessageAppResponseItem.setAutoZx(TypeData.HZICBC.getCode().equals(typeData));
		}
		return otherMessageAppResponseItem;
   }
}
